var pasteSource = "";

function copyProfile(source, target, clear) {
	var util = new Verbum.Utilities();
	util.request({
	    params: { 
	       action: "profile_manager", 
	       op: 'copy',
	       target: target,
	       source: source,
	       clear: clear
	      }											
	});

	util.on({
		'done': function() {
			Ext.Msg.message(String.format(_('{0} copied.'),translate(pasteSource)));
			this.purgeListeners();
		}
	});
}

MyDesktop.ProfileManager = Ext.extend(Ext.app.Module, {

    init : function(){
        this.launcher = {
            text: _('Profile Manager'),
            iconCls: 'profile_man',
            handler : this.createWindow,
            windowId : 'ProfileAdmin',
            scope: this
        }
    },

    createWindow : function(src){
        var desktop = this.app.getDesktop();
        var winname = src.windowId;
        var win = desktop.getWindow(winname);

        if(!win){
            var tree = new Ext.tree.TreePanel({
                animate:true, 
                autoScroll:true,
                useArrows: true,
		        loader: new Ext.tree.TreeLoader({
		            dataUrl:getMainUrl('action=profile_manager'),
		        }),
                containerScroll: true,
                rootVisible: false,
		        root: new Ext.tree.AsyncTreeNode({
		            id:'id'
		        }),
		        region: 'north',
		        split: true,
		        height: 220
            });

		    var checkColumn = new Ext.grid.CheckColumn({
		       header: _('Active'),
		       dataIndex: 'active',
		       width: 55
		    });

			var grid = new Ext.grid.GridPanel({
				id: 'profileManGrid',
		        store: new Ext.data.Store({
		        	pruneModifiedRecords: true,
					reader: new Ext.data.JsonReader({
						root: 'results',
						id: 'id'
						},[
							{name: 'name'},
							{name: 'active', type: 'bool'},
					]),
					proxy: new Ext.data.HttpProxy({
						url: getMainUrl(),
						method: 'POST'
					}),
					baseParams: {action: 'profile_manager', op: 'load'},
					autoLoad: false,
		        }),
		        plugins:checkColumn,
		        clicksToEdit:1,
		        columns: [
		            	{
		            		header: _('Action'),
		            		dataIndex: 'name',
		            		width: 230,
		            		sortable: false,
		            	},checkColumn],
				region: 'center',
			    bbar: new Ext.StatusBar({
			        id: 'profile-status-bar',
			        text: '',
			        /*items: ['->',{
							text: _('Save'),
							iconCls: 'save',
							handler: function() {
								 grid.getStore().commitChanges();
							}			            
			        	}]*/
			    }),				
			});
			
			checkColumn.on({
				'datachanged': {
					fn: function(el) {
						grid.getStore().commitChanges();
					}
				},				
			});
			
			grid.getStore().on({

				'update': {
					fn: function(store,record,op) {
						if (Ext.data.Record.COMMIT==op) {

							Verbum.Util.request({
					            params: { 
					               action: "profile_manager", 
					               node: store.node,
					               parent: store.parentNode,
					               id:  record.id,
					               value: record.get('active'),
					               op: 'save'
					              }											
							});
							
						}
					}
				}	
			});

			var ct = new Ext.Panel({
				frame: false,
				width: 640,
				height: 480,
				layout: 'border',
				items: [
					tree,
					grid
				]
			});
			
			tree.on({
				'click': {
					fn: function(node, ev) {
						if (node.isLeaf()) {
							grid.getStore().node = node.id;
							grid.getStore().parentNode = node.parentNode.id;
							grid.getStore().load({params: {parent: node.parentNode.id, id: node.id }});
							nodeId = node.parentNode.id;
						} else {
							nodeId = node.id;
						}

						var util = new Verbum.Utilities();
						util.request({
				            params: { 
				               action: "profile_manager", 
				               id:  nodeId,
				               op: 'check'
				              }											
						});
						
						util.on({
							'done': function(response) {
								obj = Ext.util.JSON.decode(response.responseText);
								if (obj.ret=="true") {
									grid.getBottomToolbar().setStatus({
										text: _('The current group has a global attribute active.'),
										iconCls: 'info-icon',	
									});
								} else {
									grid.getBottomToolbar().clearStatus();
								}
							}
						});														
						
					}
				},
				
				'contextmenu' : {
					fn: function (node, e) {
						e.stopEvent();
						if (!node.isLeaf()) {
						    var listContextMenu = new Ext.menu.Menu({
						    	items: [
						    		{
						    			id: 'copyProfile',
						    			iconCls: 'copy',
						    			text: _('Copy'),
						    			handler: function() {
						    				pasteSource = node.id;
						    				Ext.getCmp('pasteProfile').enable();
						    			}
						    		},
						    		{
						    			id: 'pasteProfile',
						    			iconCls: 'paste',
						    			text: _('Paste'),
						    			disabled: true,
						    			handler: function() {
						    				if (node.id==pasteSource) {
						    					Ext.Msg.error('Cannot paste here!');
						    				} else {
												Verbum.Util.confirm(String.format(_('Copy the values from {0} to {1} ?'),
													translate(pasteSource),
													translate(node.id)), 
													function() {
														Verbum.Util.confirm(_('Clear the target group before copy?'),
															function() { copyProfile(pasteSource,node.id,true) },
															function() { copyProfile(pasteSource,node.id,false) });														
													});	
						    				}
						    			}
						    		}
						    	]
						    });
						    if (pasteSource!="") Ext.getCmp('pasteProfile').enable();
						    listContextMenu.showAt(e.getXY());
						}
					}
				},
				
            	'beforeload': function() {
					this.lMask = new Ext.LoadMask(ct.el, {msg: _('Loading...'), removeMask: true});
			    	this.lMask.show();
            	},
            	'load': function() {
            		this.lMask.hide();
            	},
            	'loadexception': function() {
            		this.lMask.hide();
            	},/*
            	'beforeexpandnode': function() {
            		this.collapseAll();
            	}*/
			})

            win = desktop.createWindow({
				id: winname,
				closable:true,
				width:640,
				height:480,
				plain:true,
				layout: 'fit',
				iconCls: src.iconCls,
				items: ct,
				title: src.text,
            });
            
        }
        win.show();

    },
    
	display : function(){
        this.createWindow();
	}
});

/*
Ext.grid.CheckColumn.prototype ={
    init : function(grid){
        this.grid = grid;
        this.grid.on('render', function(){
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },

    onMouseDown : function(e, t){
        if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
            e.stopEvent();
            var index = this.grid.getView().findRowIndex(t);
            var record = this.grid.store.getAt(index);
            record.set(this.dataIndex, !record.data[this.dataIndex]);
        }
    },

    renderer : function(v, p, record){
        p.css += ' x-grid3-check-col-td';
        return '<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'">&#160;</div>';
    }
};*/